﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.UI.WebControls;

using CharityGamesOnline.Modules.Charity;
using CharityGamesOnline.Modules.Game;
using CharityGamesOnline.Modules.Common;
using Telerik.Web.UI;

namespace CharityGamesOnline.Modules.Event
{
    public partial class EventEdit : CGOBase
    {
        #region "Private Members"

        private int eventID = 0;
        private const int INTERVAL_MIN = 30;

        #endregion

        public int EventID
        {
            get
            {
                if (eventID == 0)
                {
                    if ((Request.QueryString["EventID"] != null))
                    {
                        eventID = Int32.Parse(Request.QueryString["EventID"]);
                    }
                }
                return eventID;
            }
        }


        #region "Event Handlers"
        protected void Page_Load(object sender, EventArgs e)
        {
            // Determine EventID to Update 
            InitialScript();

            if (!Page.IsPostBack)
            {
                string PopupScript = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtStartDate);
                imgStartDate.Attributes.Add("onclick", "dnn.dom.getById('" + txtStartDate.ClientID + "').focus();" + PopupScript);
                PopupScript = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtEndDate);
                imgEndDate.Attributes.Add("onclick", "dnn.dom.getById('" + txtEndDate.ClientID + "').focus();" + PopupScript);
                chkAllDayEvent.Attributes.Add("onclick", "javascript:showTimes('" + chkAllDayEvent.ClientID + "','" 
                    + ddlStartTime.ClientID + "','" + ddlEndTime.ClientID + "');");
                chkSignUp.Attributes.Add("onclick", "javascript:showPayment('" + chkSignUp.ClientID + "','" 
                    + trPaymentType.ClientID + "','" + trMaxEnrollment.ClientID + "');");
                chkDisplayImage.Attributes.Add("onclick", "javascript:showImage('" + chkDisplayImage.ClientID + "','" 
                    + trImageURL.ClientID + "','" + trWidth.ClientID + "','" + trHeight.ClientID+ "');");
                
                
                InitialTimeDropdownList();
                
                BindData();
                BindCharityData();
                BindGameData();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }        

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Globals.NavigateURL(), true);
            }
            catch (Exception exc)
            {
                //Module failed to load 
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                EventController ctrlEvent = new EventController();

                EventInfo objEvent = new EventInfo();

                
                objEvent.PortalID = PortalId;
                objEvent.EventID = EventID;
                objEvent.LastUpdatedID = UserId;
                
                objEvent.Name = txtEventName.Text;
                objEvent.AllDayEvent = chkAllDayEvent.Checked;

                if (chkAllDayEvent.Checked)
                {
                    objEvent.DateBegin = ConvertDateStringstoDatetime(txtStartDate.Text, "00:00");
                    objEvent.DateEnd = ConvertDateStringstoDatetime(txtEndDate.Text, "23:59");
                }
                else
                {
                    objEvent.DateBegin = ConvertDateStringstoDatetime(txtStartDate.Text, ddlStartTime.SelectedValue);
                    objEvent.DateEnd = ConvertDateStringstoDatetime(txtEndDate.Text, ddlEndTime.SelectedValue);
                }

                objEvent.Description = txtDescription.Text;

                objEvent.Signups = chkSignUp.Checked;
                if (rblFree.Checked)
                    objEvent.EnrollType = rblFree.Value;
                else if (rblPaid.Checked)
                    objEvent.EnrollType = rblPaid.Value;

                if (string.IsNullOrEmpty(txtEnrollFee.Text.Trim()))
                    objEvent.EnrollFee = 0;
                else
                    objEvent.EnrollFee = decimal.Parse(txtEnrollFee.Text);
                if (string.IsNullOrEmpty(txtMaxEnrollment.Text.Trim()))
                    objEvent.MaxEnrollment = 0;
                else
                    objEvent.MaxEnrollment = int.Parse(txtMaxEnrollment.Text);

                if (chkDisplayImage.Checked)
                {                    
                    if (ctlURL.UrlType == "F" && ctlURL.Url.StartsWith("FileID="))
                    {
                        int fieldID = int.Parse(ctlURL.Url.Substring(7));
                        FileController ctrlFile = new FileController();
                        FileInfo objFile = ctrlFile.GetFileById(fieldID, PortalId);
                        if (string.IsNullOrEmpty(txtWidth.Text) || txtWidth.Text.Trim() == "0")
                        {
                            txtWidth.Text = objFile.Width.ToString();
                        }

                        if (string.IsNullOrEmpty(txtHeight.Text) || txtHeight.Text.Trim() == "0")
                        {
                            txtHeight.Text = objFile.Height.ToString();
                        }
                    }
                }

                objEvent.ImageDisplay = chkDisplayImage.Checked;
                objEvent.ImageType = ctlURL.UrlType;
                objEvent.ImageURL = ctlURL.Url;

                if (string.IsNullOrEmpty(txtWidth.Text))
                    objEvent.ImageWidth = 0;
                else
                    objEvent.ImageWidth = int.Parse(txtWidth.Text.Trim());

                if (string.IsNullOrEmpty(txtHeight.Text))
                    objEvent.ImageHeight = 0;
                else
                    objEvent.ImageHeight = int.Parse(txtHeight.Text.Trim());



                eventID = ctrlEvent.SaveEvent(objEvent);

                ctrlEvent.DeleteEventCharity(PortalId, EventID);
                if (ddlCharity.SelectedIndex != Null.NullInteger && !string.IsNullOrEmpty(ddlCharity.SelectedValue))
                {
                    ctrlEvent.AddEventCharity(PortalId, EventID, Int32.Parse(ddlCharity.SelectedValue));
                }

                ctrlEvent.DeleteEventGame(PortalId, EventID);
                if (ddlGame.SelectedIndex != Null.NullInteger && !string.IsNullOrEmpty(ddlGame.SelectedValue))
                {
                    ctrlEvent.AddEventGame(PortalId, EventID, Int32.Parse(ddlGame.SelectedValue));
                }

                // Redirect back to the portal home page 
                Response.Redirect(Globals.NavigateURL(), true);
            }
            catch (Exception exc)
            {
                //Module failed to load 
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// ----------------------------------------------------------------------------- 
        /// <summary> 
        /// cmdDelete_Click runs when the delete button is clicked 
        /// </summary> 
        /// <remarks> 
        /// </remarks> 
        /// <history> 
        /// </history> 
        /// ----------------------------------------------------------------------------- 
        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            try
            {
                // Only attempt to delete the item if it exists already 
                if (EventID>0)
                {
                    EventController ctrlEvent = new EventController();
                    ctrlEvent.DeleteEvent(PortalId, EventID);
                }
                // Redirect back to the portal home page 
                Response.Redirect(Globals.NavigateURL(), true);
            }
            catch (Exception exc)
            {
                //Module failed to load 
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion

        #region Private Function        

        private void InitialScript()
        {
            string csName = string.Empty;
            string csText = string.Empty;
            Type csType = System.Reflection.MethodBase.GetCurrentMethod().GetType();

            csName = "ExtValidationScriptFile";
            csText = "<script src=\"" + ResolveUrl("Script/Validation.js") + "\" type=\"text/javascript\"></script>";
            if (!Page.ClientScript.IsClientScriptBlockRegistered(csName))
            {
                Page.ClientScript.RegisterClientScriptBlock(csType, csName, csText);
            }            
        }

        private void InitialTimeDropdownList()
        {
            DateTime Today = ConvertDateStringstoDatetime(DateTime.Now.Date.ToShortDateString(), "00:00");
            DateTime Tommorrow = Today.AddDays(1);
            while (Today < Tommorrow)
            {                
                ddlStartTime.Items.Add(new RadComboBoxItem(Today.ToShortTimeString(), Today.ToString("HH:mm", CultureInfo.InvariantCulture)));
                ddlEndTime.Items.Add(new RadComboBoxItem(Today.ToShortTimeString(), Today.ToString("HH:mm", CultureInfo.InvariantCulture)));

                if (Today > DateTime.Now && ddlStartTime.SelectedIndex == 0)
                {
                    ddlStartTime.SelectedIndex = ddlStartTime.Items.Count - 1;
                }

                Today = Today.AddMinutes(INTERVAL_MIN);                
            }

            if (ddlStartTime.SelectedIndex > 0)
            {
                if (ddlStartTime.SelectedIndex == ddlStartTime.Items.Count - 1)
                {
                    ddlEndTime.SelectedIndex = 0;
                }
                else
                {
                    ddlEndTime.SelectedIndex = ddlStartTime.SelectedIndex + 1;
                }
            }
 
        }

        private void BindData()
        {
            if (EventID>0)
            {
                EventController ctrlEvent = new EventController();
                GameEnrollmentController ctrlEnroll = new GameEnrollmentController();
                EventInfo objEvent = ctrlEvent.GetEvent(PortalId, EventID);

                if (!Null.IsNull(objEvent))
                {
                    txtEventName.Text = objEvent.Name;
                    chkAllDayEvent.Checked = objEvent.AllDayEvent;

                    if (chkAllDayEvent.Checked)
                    {
                        ddlStartTime.Attributes.Add("style", "display:none;");
                        ddlEndTime.Attributes.Add("style", "display:none;");
                    }
                    txtStartDate.Text = objEvent.DateBegin.ToShortDateString();
                    txtEndDate.Text = objEvent.DateEnd.ToShortDateString();                    
                                        
                    ddlStartTime.SelectedIndex = ddlStartTime.FindItemIndexByValue(objEvent.DateBegin.ToString("HH:mm", CultureInfo.InvariantCulture));
                    ddlEndTime.SelectedIndex = ddlEndTime.Items.FindItemIndexByValue(objEvent.DateEnd.ToString("HH:mm", CultureInfo.InvariantCulture));

                    txtDescription.Text = objEvent.Description;
                    chkSignUp.Checked = objEvent.Signups;
                    if (chkSignUp.Checked)
                    {
                        trPaymentType.Attributes.Add("style", "");
                        trMaxEnrollment.Attributes.Add("style", "");
                    }

                    if (objEvent.EnrollType == rblFree.Value)
                        rblFree.Checked = true;
                    if (objEvent.EnrollType == rblPaid.Value)
                        rblPaid.Checked = true;

                    txtEnrollFee.Text = objEvent.EnrollFee.ToString();
                    txtMaxEnrollment.Text = objEvent.MaxEnrollment.ToString();
                    txtEnrolled.Text = ctrlEnroll.GetPlayedCount(PortalId, objEvent.EventID).ToString();

                    chkDisplayImage.Checked = objEvent.ImageDisplay;
                    if (chkDisplayImage.Checked)
                    {
                        trImageURL.Attributes.Add("style", "");
                        trWidth.Attributes.Add("style", "");
                        trHeight.Attributes.Add("style", "");
                    }
                    ctlURL.UrlType = objEvent.ImageType;
                    ctlURL.Url = objEvent.ImageURL;
                    txtHeight.Text = objEvent.ImageHeight.ToString();
                    txtWidth.Text = objEvent.ImageWidth.ToString();                        
                }
                else
                {
                    // security violation attempt to access item not related to this Module 
                    Response.Redirect(Globals.NavigateURL(), true);
                }

            }
            else
            {
                txtStartDate.Text = DateTime.Now.ToShortDateString();
                txtEndDate.Text = DateTime.Now.ToShortDateString();
                txtMaxEnrollment.Text = "0";
                cmdDelete.Visible = false;
                //ctlAudit.Visible = false;
            }
        }

        private void BindCharityData()
        {            
            CharityController ctrlCharity = new CharityController();
            List<CharityInfo> lsCharity = ctrlCharity.GetCharities(PortalId);
            List<CharityInfo> lsEventCharity = ctrlCharity.GetCharities(PortalId, EventID);

            ddlCharity.DataSource = lsCharity;
            ddlCharity.DataBind();
            ddlCharity.Items.Insert(0, new RadComboBoxItem(Localization.GetString("defaultSelectedCharity", LocalResourceFile), string.Empty));
            if (lsEventCharity.Count > 0)
            {
                foreach (CharityInfo objCharity in lsEventCharity)
                {
                    ddlCharity.SelectedIndex = ddlCharity.FindItemIndexByValue(objCharity.CharityID.ToString(), false);
                    break;
                }
            }
            else
                ddlCharity.SelectedIndex = 0;
        }

        private void BindGameData()
        {
            GameController ctrlGame = new GameController();
            List<GameInfo> lsGame = ctrlGame.GetGames();
            List<GameInfo> lsEventGame = ctrlGame.GetGames(PortalId, EventID);

            ddlGame.DataSource = lsGame;
            ddlGame.DataBind();
            ddlGame.Items.Insert(0, new RadComboBoxItem(Localization.GetString("defaultSelectedGame", LocalResourceFile), string.Empty));
            if (lsEventGame.Count > 0)
            {
                foreach (GameInfo objGame in lsEventGame)
                {
                    ddlGame.SelectedIndex = ddlGame.FindItemIndexByValue(objGame.GameID.ToString(), false);
                    break;
                }
            }
            else
                ddlGame.SelectedIndex = 0;

        }
        #endregion
    }
}